<?php
// FEzco 233190639
session_start();
// Verify login status
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

// Database connection (for logging operations, if needed; otherwise, comment out)
require 'db_connect.php';

// Product data file path (adjust based on actual directory structure)
$jsonFile = '../data/products.json';
$error = '';
$success = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data and sanitize
    $product = [
        'id' => uniqid(), // Generate unique ID (or use auto-increment ID)
        'name' => trim($_POST['name']),
        'price' => (float)$_POST['price'],
        'original_price' => (float)$_POST['original_price'],
        'quantity' => (int)$_POST['quantity'],
        'description' => trim($_POST['description']),
        'image_url' => '3.jpg', 
        'supplier' => trim($_POST['supplier']),
        'category' => trim($_POST['category']),
        'discount' => (int)$_POST['discount'],
        'origin_country' => trim($_POST['origin_country']),
        'roast_level' => trim($_POST['roast_level'])
    ];

    // Basic validation
    if (empty($product['name']) || empty($product['price']) || empty($product['category'])) {
        $error = "Product name, price, and category are required";
    } elseif ($product['discount'] < 0 || $product['discount'] > 100) {
        $error = "Discount must be between 0 and 100";
    } else {
        try {
            // Read existing product data
            if (file_exists($jsonFile)) {
                $existingData = json_decode(file_get_contents($jsonFile), true);
                if (!is_array($existingData)) {
                    $existingData = []; 
                }
            } else {
                $existingData = [];
            }

            // Add new product (if using auto-increment ID, change to: max_id + 1)
            $existingData[] = $product;

            // Write updated JSON file (indent 2 spaces for readability)
            file_put_contents($jsonFile, json_encode($existingData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            
            $success = "Product added successfully!";
            // Clear form fields
            $_POST = [];
        } catch (Exception $e) {
            $error = "Add failed: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Product</title>
    <style>
        /* Add product form - Maintain consistent with admin panel */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
        }
        .header {
            background: url('../head.jpg') center/cover no-repeat;
            padding: 20px 0;
            margin-bottom: 30px;
        }
        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            height: 40px; /* Maintain consistent small logo with login page */
            width: auto;
        }
        .nav a {
            color: #fff;
            text-decoration: none;
            margin-left: 15px;
            text-shadow: 1px 1px 3px rgba(0,0,0,0.5);
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        h1 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.8rem;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 500;
        }
        input, select, textarea {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
        }
        textarea {
            min-height: 100px;
            resize: vertical;
        }
        .form-actions {
            margin-top: 20px;
        }
        .btn {
            display: inline-block;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            text-decoration: none;
        }
        .btn-primary {
            background-color: #4CAF50; /* Use consistent green for add button */
            color: white;
        }
        .btn-secondary {
            background-color: #6b4226; /* Maintain theme brown */
            color: white;
            margin-left: 10px;
        }
        .error {
            color: #e63946;
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #f8d7da;
            border-radius: 4px;
        }
        .success {
            color: #28a745;
            margin-bottom: 15px;
            padding: 10px;
            border: 1px solid #c3e6cb;
            border-radius: 4px;
        }
        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        @media (max-width: 768px) {
            .form-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- Header - Maintain consistent with admin panel -->
    <header class="header">
        <div class="header-content">
            <img src="../logo.jpg" alt="Fezco Logo" class="logo">
            <nav class="nav">
                <a href="index.php">Product List</a>
                <a href="../products.php">View Store</a>
                <a href="logout.php">Logout</a>
            </nav>
        </div>
    </header>

    <div class="container">
        <h1>Add New Product</h1>

        <?php if ($error): ?>
            <div class="error"><?php echo $error; ?></div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="success"><?php echo $success; ?></div>
        <?php endif; ?>

        <!-- Add product form -->
        <form method="POST">
            <div class="form-grid">
                <div class="form-group">
                    <label for="name">Product Name *</label>
                    <input type="text" id="name" name="name" 
                           value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>" 
                           required>
                </div>

                <div class="form-group">
                    <label for="price">Price ($) *</label>
                    <input type="number" id="price" name="price" step="0.01" min="0" 
                           value="<?php echo isset($_POST['price']) ? htmlspecialchars($_POST['price']) : ''; ?>" 
                           required>
                </div>

                <div class="form-group">
                    <label for="original_price">Original Price ($)</label>
                    <input type="number" id="original_price" name="original_price" step="0.01" min="0" 
                           value="<?php echo isset($_POST['original_price']) ? htmlspecialchars($_POST['original_price']) : ''; ?>">
                </div>

                <div class="form-group">
                    <label for="quantity">Quantity</label>
                    <input type="number" id="quantity" name="quantity" min="0" 
                           value="<?php echo isset($_POST['quantity']) ? htmlspecialchars($_POST['quantity']) : 0; ?>">
                </div>

                <div class="form-group">
                    <label for="category">Category *</label>
                    <select id="category" name="category" required>
                        <option value="single origin" <?php echo (isset($_POST['category']) && $_POST['category'] == 'single origin') ? 'selected' : ''; ?>>Single Origin</option>
                        <option value="blend" <?php echo (isset($_POST['category']) && $_POST['category'] == 'blend') ? 'selected' : ''; ?>>Blend</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="discount">Discount (%)</label>
                    <input type="number" id="discount" name="discount" min="0" max="100" 
                           value="<?php echo isset($_POST['discount']) ? htmlspecialchars($_POST['discount']) : 0; ?>">
                </div>

                <div class="form-group">
                    <label for="supplier">Supplier</label>
                    <input type="text" id="supplier" name="supplier" 
                           value="<?php echo isset($_POST['supplier']) ? htmlspecialchars($_POST['supplier']) : ''; ?>">
                </div>

                <div class="form-group">
                    <label for="origin_country">Origin Country</label>
                    <input type="text" id="origin_country" name="origin_country" 
                           value="<?php echo isset($_POST['origin_country']) ? htmlspecialchars($_POST['origin_country']) : ''; ?>">
                </div>

                <div class="form-group">
                    <label for="roast_level">Roast Level</label>
                    <select id="roast_level" name="roast_level">
                        <option value="Light" <?php echo (isset($_POST['roast_level']) && $_POST['roast_level'] == 'Light') ? 'selected' : ''; ?>>Light</option>
                        <option value="Medium-Light" <?php echo (isset($_POST['roast_level']) && $_POST['roast_level'] == 'Medium-Light') ? 'selected' : ''; ?>>Medium-Light</option>
                        <option value="Medium" <?php echo (isset($_POST['roast_level']) && $_POST['roast_level'] == 'Medium') ? 'selected' : ''; ?>>Medium</option>
                        <option value="Dark" <?php echo (isset($_POST['roast_level']) && $_POST['roast_level'] == 'Dark') ? 'selected' : ''; ?>>Dark</option>
                        <option value="Extra Dark" <?php echo (isset($_POST['roast_level']) && $_POST['roast_level'] == 'Extra Dark') ? 'selected' : ''; ?>>Extra Dark</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="description">Description</label>
                <textarea id="description" name="description"><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">Save Product</button>
                <a href="index.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</body>
</html>